<script setup lang="ts">
import type { SysReceiptRecordDetails } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getSysReceiptRecordDetails } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import DetailCard from '@/components/DetailCard.vue'
import { useFlow } from '@/hooks/useFlow'

// 定义页面配置
definePage({
  style: {
    navigationBarTitleText: '后台登记资金详情',
  },
})

// 使用流程相关功能
const { currentProcess, getProcessInstance, getCurrentUserPendingTaskId, loading } = useFlow()

// 业务详情数据
const businessData = ref<SysReceiptRecordDetails | null>(null)
const errorMessage = ref('')
const flowIdValue = ref<string>('')
const idValue = ref<string>('')

// 计算基本信息列表
const basicInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '业务编号',
      value: businessData.value.businessNo || '--',
    },
    {
      label: '票据类型',
      value: businessData.value.billType?.toString() || '--',
    },
    {
      label: '渠道类型',
      value: businessData.value.channelType || '--',
    },
    {
      label: '渠道名称',
      value: businessData.value.channelName || '--',
    },
    {
      label: '收款事项',
      value: businessData.value.receiptEvent || '--',
    },
    {
      label: '票据号码',
      value: businessData.value.billNumber || '--',
    },
  ]
})

// 计算金额信息列表
const amountInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '金额',
      value: businessData.value.amount ?? 0,
      type: 'currency',
    },
    {
      label: '退款金额',
      value: businessData.value.refundAmount ?? 0,
      type: 'currency',
    },
    {
      label: '剩余金额',
      value: businessData.value.remainingAmount ?? 0,
      type: 'currency',
    },
    {
      label: '认领金额',
      value: businessData.value.claimAmount ?? 0,
      type: 'currency',
    },
  ]
})

// 计算收款方信息列表
const receivingInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '收款账户',
      value: businessData.value.receivingAccount || '--',
    },
    {
      label: '收款银行',
      value: businessData.value.receivingBank || '--',
    },
    {
      label: '收款实体',
      value: businessData.value.receivingEntity || '--',
    },
    {
      label: '收款手机号',
      value: businessData.value.receivingPhone || '--',
    },
  ]
})

// 计算付款方信息列表
const payerInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '付款账户',
      value: businessData.value.payerAccount || '--',
    },
    {
      label: '付款银行',
      value: businessData.value.payerBank || '--',
    },
    {
      label: '付款实体',
      value: businessData.value.payerEntity || '--',
    },
    {
      label: '付款手机号',
      value: businessData.value.payerPhone || '--',
    },
  ]
})

// 计算业务相关信息列表
const businessInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '业务机构',
      value: businessData.value.businessInstitutionName || '--',
    },
    {
      label: '业务部门',
      value: businessData.value.businessDepartmentName || '--',
    },
    {
      label: '业务员',
      value: businessData.value.salesmanName || '--',
    },
    {
      label: '销售员',
      value: businessData.value.salesperson || '--',
    },
  ]
})

// 计算时间信息列表
const timeInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '创建时间',
      value: businessData.value.createTime || '--',
      type: 'datetime',
    },
    {
      label: '付款时间',
      value: businessData.value.payTime || '--',
      type: 'datetime',
    },
  ]
})

// 计算状态和其他信息列表
const statusInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '状态',
      value: businessData.value.status?.toString() || '--',
    },
    {
      label: '是否退款',
      value: businessData.value.isRefund === 1 ? '是' : (businessData.value.isRefund === 0 ? '否' : '--'),
    },
    {
      label: '是否认领',
      value: businessData.value.isClaim === 1 ? '是' : (businessData.value.isClaim === 0 ? '否' : '--'),
    },
    {
      label: '备注',
      value: businessData.value.remark || '--',
      forceMultiline: true,
    },
  ]
})

// 获取业务详情数据
async function getBusinessData() {
  try {
    if (idValue.value) {
      await getProcessInstance(idValue.value)
      // 获取当前用户待审批任务ID
      const taskId = await getCurrentUserPendingTaskId(idValue.value)
      if (taskId) {
        flowIdValue.value = taskId
      }
      if (currentProcess.value) {
        const res = await getSysReceiptRecordDetails(currentProcess.value.businessKey)
        businessData.value = res.data || null
      }
    }
  }
  catch (error) {
    console.error('获取业务详情失败:', error)
    errorMessage.value = '获取业务详情失败，请重试'
  }
}

// 页面加载时获取数据
onLoad(async (e: any) => {
  if (e.flowId) {
    flowIdValue.value = e.flowId
  }
  if (e.id) {
    idValue.value = e.id
    getBusinessData()
  }
})

// 页面显示时重新获取数据
onShow(async () => {
  if (idValue.value) {
    await getBusinessData()
  }
})
</script>

<template>
  <view class="container bg-slate-50">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
    <view class="content">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        加载中...
      </view>

      <!-- 错误状态 -->
      <view v-else-if="errorMessage" class="error-container">
        <text>{{ errorMessage }}</text>
        <button class="retry-btn" @click="getBusinessData">
          重新加载
        </button>
      </view>

      <!-- 使用DetailCard组件展示详情信息 -->
      <template v-else-if="businessData">
        <!-- 基本信息 -->
        <DetailCard title="基本信息" :info-list="basicInfo" />

        <!-- 金额信息 -->
        <DetailCard title="金额信息" :info-list="amountInfo" />

        <!-- 收款方信息 -->
        <DetailCard title="收款方信息" :info-list="receivingInfo" />

        <!-- 付款方信息 -->
        <DetailCard title="付款方信息" :info-list="payerInfo" />

        <!-- 业务相关信息 -->
        <DetailCard title="业务信息" :info-list="businessInfo" />

        <!-- 时间信息 -->
        <DetailCard title="时间信息" :info-list="timeInfo" />

        <!-- 状态和其他信息 -->
        <DetailCard title="状态信息" :info-list="statusInfo" />
      </template>
    </view>

    <!-- 审批操作栏 -->
    <view class="approval-bar">
      <ApprovalActionBar
        v-if="flowIdValue && currentProcess?.status === 1"
        :process-id="flowIdValue"
      />
    </view>
  </view>
</template>

<style scoped>
.container {
  padding-bottom: 20px;
}

.content {
  padding: 20rpx;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.error-container {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

.retry-btn {
  margin-top: 16px;
  padding: 8px 24px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
}
</style>
